<?php

namespace App\Model\Common;

class ProjectCategory extends Common
{
    protected $cacheKey = 'ap:category:list';
    protected $parentCacheKey = 'ap:project:category:list';
    protected $parentKey = 'project_id';

    public function getProjectCategoryList($projectid, $opt = [])
    {
        if (config('app.redis_on') && empty($opt['no_cache'])) {
            $data = Redis::hget($this->parentCacheKey, $projectid);
        }
        if (empty($data)) {
            $data = self::where('project_id', $projectid)->get();
            if (!$data) {
                return [];
            }
            $data = $this->formatOneDbData($data, $opt);
            if (config('app.redis_on')) {
                Redis::hset($this->parentCacheKey, $projectid, json_encode($data));
            }
        } else {
            $data = json_decode($data, true);
        }

        return $data;
    }

    public function formatOneDbData($data, $opt = [])
    {
        if (!empty($opt['user'])) {
            $newData = [];
            foreach ($data as $k => $v) {
                $newData[$k]['id'] = $data[$k]['id'];
                $newData[$k]['title'] = $data[$k]['title'];
                $newData[$k]['vname'] = $data[$k]['vname'];
                $newData[$k]['user_id'] = $data[$k]['user_id'];
                $newData[$k]['project_id'] = $data[$k]['project_id'];
            }

            return $newData;
        } else {
            return $data;
        }
    }

    public function refreshCache($obj, $mode)
    {
        if ('insert' === $mode) {
            $this->getOne($obj->id, ['no_cache' => true]);
            $this->getListByParentKey($obj->project_id, ['user' => true, 'no_cache' => true]);
        } elseif ('update' === $mode) {
            $this->getOne($obj->input('id'), ['no_cache' => true]);
            $this->getListByParentKey($obj->input('project_id'), ['user' => true, 'no_cache' => true]);
        }
    }

    public function listDataFormat($list, $opt = [])
    {
        $Project = new Project();
        foreach ($list as $key => $value) {
            $projectid = $value['project_id'];
            $project = $Project->getOne($projectid);
            $list[$key]['project_title'] = $project['title'];
        }
        return $list;
    }
}
